import React, {FC} from 'react';
import "./index.less";
import {useRequest} from "ahooks";
import * as API from "@/services";
import {Empty, Spin} from "antd";
import {HxArticleNormalItem} from "@/components/HxArticleItem";
import {FrontArticleCollection} from "@/services";
import HxPagination from "@/components/HxPagination";

interface FavoriteArticleProps {
}

/**
 * 文章收藏 页面
 */
const FavoriteArticle: FC<FavoriteArticleProps> = (props) => {
  const recordsReq = useRequest((p) => API.queryMineFavArticles({
    pageSize: 10,
    ...p,
  }), {
    refreshDeps: []
  });

  const data = recordsReq.data?.data || [];

  return (
    <div className={"favorite-article-container"}>
      <Spin spinning={recordsReq.loading}>
        {
          data.length > 0 ? (
            data.map((item) => (
              <HxArticleNormalItem key={item.id} article={item.article} onArticleChange={(article) => {
                recordsReq?.mutate((oldData) => {
                  const ret = {
                    ...oldData,
                    data: oldData!.data.map((d) => {
                      if (d.article?.id === article.id) {
                        return {
                          ...d,
                          article
                        }
                      }
                      return d;
                    })
                  } as API.RespPageResult<API.FrontArticleCollection>;
                  return ret;
                })
              }}/>
            ))
          ) : (
            <Empty/>
          )
        }
        {
          recordsReq.data && (
            <div className={"hx-pagination-wrapper"}>
              <HxPagination size="default"
                            total={recordsReq.data?.total}
                            current={recordsReq.data.current}
                            pageSize={recordsReq.data.pageSize}
                            onChange={(pageNum, pageSize) => {
                              recordsReq.run({
                                page: pageNum,
                                pageSize
                              })
                            }}
              />
            </div>
          )
        }
      </Spin>
    </div>
  );
};

export default FavoriteArticle;
